package com.hzw.service;

import com.hzw.api.ILoginAndRegisterService;
import com.hzw.common.DateUtils;
import com.hzw.dao.LoginAndRegisterDao;
import com.hzw.dao.UserDao;
import com.hzw.entity.Admin;
import com.hzw.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class LoginAndRegisterService implements ILoginAndRegisterService {

    @Autowired
    LoginAndRegisterDao loginAndRegisterDao;

    @Autowired
    UserDao userDao;


    /**
     * 查询用户（用过用户名）
     * @param username
     * @return
     */
    @Override
    public User selectByUserName(String username) {
        return loginAndRegisterDao.selectByUserName(username);
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public int registerUser(User user) {
        User res = loginAndRegisterDao.selectByUserName(user.getUsername());
        if(res == null){
            user.setId(UUID.randomUUID().toString().replace("-", ""));
            user.setStatus(0);
            user.setRegisterTime(DateUtils.getNowTime());
            userDao.insert(user);
            return 1;
        }
        return 0;
    }

    /**
     * 用户登录
     * @param user
     * @return
     */
    @Override
    @Transactional
    public Object loginUser(User user) {
        User res = loginAndRegisterDao.loginUser(user.getUsername(), user.getPassword());
        if (res != null && res.getStatus().equals(0)){
            res.setLoginTime(DateUtils.getNowTime());
            userDao.updateById(res);
            return res;
        }else if (res != null && res.getStatus().equals(1)){
            return "stop";
        }
        return "unDefind";
    }

    /**
     * 管理员登录
     * @param admin
     * @return
     */
    @Override
    public Object loginAdmin(Admin admin) {
        Admin res = loginAndRegisterDao.loginAdmin(admin.getUsername(), admin.getPassword());
        if (res != null && res.getStatus().equals(0)){
            return res;
        }else if (res != null && res.getStatus().equals(1)){
            return "stop";
        }
        return "unDefind";
    }
}
